<?php
namespace app\admin\controller\order\service;
use app\admin\model\order\OrderModel;
use EasyWeChat\Factory;

class OrderDrive
{
    public $mchConfig;
    public $offConfig;
    public function __construct()
    {
        $config = get_option("order_setting");
        $this->mchConfig = [
            'app_id'             => $config['app_id'],
            'mch_id'             => $config['mch_id'],
            'key'                => $config['mch_key'],
            'cert_path'          => "/upload/".$config['mch_apicert_certificate'],
            'key_path'           => "/upload/".$config['mch_apikey_certificate'],
        ];
        $log_path =dirname( app_path()) . "/runtime/easywechat/".date("Ymd").""."/".date("d").'.log';
        $this->offConfig = [
            'app_id' => $config['app_id'],
            'secret' => $config['app_secret'],
            'response_type' => 'array',
            'log' => [
                'default' => config('app_debug')?'prod':'dev',
                'channels' => [
                    // 测试环境
                    'dev' => [
                        'driver' => 'single',
                        'path' => $log_path,
                        'level' => 'debug',
                    ],
                    // 生产环境
                    'prod' => [
                        'driver' => 'daily',
                        'path' => $log_path,
                        'level' => 'info',
                    ],
                ],
            ],
        ];
    }

    //用用初始化
    public function app()
    {
        return Factory::payment($this->mchConfig);
    }

    /**
     * 下单
     */
    public function place_order($param)
    {
        $order =[
            //产品名称
            'body'            => $param['product_name'],
            //产品订单号
            'out_trade_no'    => product_number(),
            //产品费用
            'total_fee'       => $param['price']*100,
            //客服端ip地址
            'spbill_create_ip'=> get_client_ip(),
            //支付回调地址
            'notify_url'      => $param['notify_url'],
            //采用支付方式
            'trade_type'      => $param['trade_type'],
            //'openid' => $this->getopenid(),
        ];
        //微信订单
        $result =$this->app()->order->unify($order);
        //本地订单
        OrderModel::create([
            "order_name"  => $order['body'],
            "order_number"=> $order['out_trade_no'],
            "user_id"     => isset($param['user_id'])?$param['user_id']:0,
            "price"       => $order['total_fee']/100,
            "status"      => 0,
            "order_type"  => isset($param['order_type'])?$param['order_type']:0,
            "desc"        => isset($param['desc'])?$param['desc']:'',
            "note"        => isset($param['note'])?$param['note']:''
        ]);
        switch ($param['trade_type'])
        {
            case 'NATIVE':
                    return qrcode($result['code_url']);
                break;
        }
    }

    //支付通知结果
    public function notice()
    {
        $response = $this->app()->handlePaidNotify(function($message, $fail)
        {
            $wxOrder = $this->app()->order->queryByOutTradeNumber($message['out_trade_no']);

            if(isset($wxOrder['trade_state']))
            {
                switch ($wxOrder['trade_state'])
                {
                    case 'SUCCESS':
                        $order = OrderModel::where("order_number",$message['out_trade_no'])->find();
                        if($order)
                        {
                            OrderModel::where("id",$order['id'])->update([
                                "status" => 1
                            ]);
                        }
                        break;
                }
            }
            return true;
        });
        $response->send();
    }




}